﻿using System.Collections.Generic;
using System.Device.Location;
using System.Linq;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Maps.Controls;
using Microsoft.Phone.Maps.Toolkit;
using SkiTracker.Model;
using SkiTracker.ViewModel;

namespace SkiTracker.View
{
    public partial class ShowFriendsPage : PhoneApplicationPage
    {
        public ShowFriendsPage()
        {
            InitializeComponent();

            DataContext = new ShowFriendsViewModel();

            ViewModel.Friends.CollectionChanged += (sender, args) =>
                {
                    BindFriends(ViewModel.Friends);
                    SetView();
                };

            ViewModel.PropertyChanged += (sender, args) =>
                {
                    if (args.PropertyName == "CurrentLocation") SetView();
                };
        }

        private void BindFriends(IEnumerable<Device> friends)
        {
            // bugfix for Databinding MapItemsControl
            MapExtensions.GetChildren(Map).OfType<MapItemsControl>().First().ItemsSource 
                = friends.Where(d => d.Coordinate != GeoCoordinate.Unknown);
        }

        private void SetView()
        {
            var visibleCoordinates = new List<GeoCoordinate>();

            if (ViewModel.Friends != null) visibleCoordinates.AddRange(ViewModel.Friends.Select(f => f.Coordinate).Where(c => c != null && c != GeoCoordinate.Unknown));
            if (ViewModel.CurrentLocation != null) visibleCoordinates.Add(ViewModel.CurrentLocation);
            if (visibleCoordinates.Count == 0) return;

            Map.SetView(LocationRectangle.CreateBoundingRectangle(visibleCoordinates));

        }

        public ShowFriendsViewModel ViewModel { get { return DataContext as ShowFriendsViewModel; } }

    }
}